﻿using System;
using System.Linq;
using Fee.Stores;
using Fee.ViewModel;
using Identity.Stores;
using JwtWebApi.Data;
using JwtWebApi.Models.Manage;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace JwtWebApi.Controllers.Manage
{
    [Authorize]
    [Route("manage/[controller]")]
    [ApiController]
    [EnableCors]
    public class FrameworkContractController : Controller
    {
        private readonly ApplicationDbContext _context;
        private readonly IProjectStore<ApplicationDbContext> _projectStore;
        private readonly IVendorStore<ApplicationDbContext> _vendorStore;
        private readonly IFrameworkContractStore<ApplicationDbContext> frameworkContractStore;

        public FrameworkContractController(ApplicationDbContext context,
            IFrameworkContractStore<ApplicationDbContext> frameworkContractStore,
            IVendorStore<ApplicationDbContext> vendorStore
            , IProjectStore<ApplicationDbContext> projectStore
        )
        {
            _context = context;
            this.frameworkContractStore = frameworkContractStore;
            _vendorStore = vendorStore ?? throw new ArgumentNullException(nameof(vendorStore));
            _projectStore = projectStore;
            ;
        }

        [HttpGet("list")]
        public IActionResult Index([FromQuery] FrameworkContractSearcher searcher)
        {
            var query = _context.FrameworkContracts
                .Include(f => f.Vendor).Where(f =>
                    (string.IsNullOrEmpty(searcher.No) || searcher.No == f.No)
                    &&
                    (searcher.ContractType == null || searcher.ContractType == f.ContractType)
                    &&
                    (searcher.Vendor == null || searcher.Vendor.Id == f.Vendor.Id)
                );
            var data = query.Skip(searcher.GetSkip())
                .Take(searcher.GetTake());

            return Json(new
            {
                data = data.Select(f => new FrameworkContractDetailViewModel(f)),
                total = query.Count()
            });
        }

        [HttpPost("save")]
        public IActionResult Save([FromBody] FrameworkContractDetailViewModel contractDetailViewModel)
        {
            var contract =
                contractDetailViewModel.ToFrameworkContract(frameworkContractStore, _vendorStore, _projectStore);

            _context.Update(contract);
            _context.SaveChanges();
            return Json(new {successed = true, message = "保存成功"});
        }

        [HttpGet("get/{id}")]
        public IActionResult Get(int id)
        {
            var contract = frameworkContractStore.GetById(id, true);
            return Json(new FrameworkContractDetailViewModel(contract));
        }
    }
}